package com.leyou.order.web;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.service.OrderService;
import com.leyou.order.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     * @param orderDTO  接收参数：支付类型、购物车数据、地址数据
     * @param result    接收异常信息：HibernateValidateble中的内容：可以参考UserController
     * @return          订单编号
     */
    @PostMapping
    public ResponseEntity<Long> createOrder(@RequestBody @Valid OrderDTO orderDTO, BindingResult result){
        if(result.hasErrors()){
            // 抛出异常
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        Long orderId = orderService.createOrder(orderDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(orderId);
    }

    /**
     * 根据id查询订单
     * @param id    订单id
     * @return      返回订单的Vo对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<OrderVO> queryOrderById(@PathVariable("id") Long id){
        OrderVO orderVO = orderService.queryOrderById(id);
        return ResponseEntity.ok(orderVO);
    }

    /**
     * 获取微信支付的二维码链接
     * @param id        乐优商城订单id编号
     * @return          微信返回的支付的链接地址
     */
    @GetMapping("/url/{id}")
    public ResponseEntity<String> getPayUrl(@PathVariable("id") Long id){
        String payUrl = orderService.getPayUrl(id);
        return ResponseEntity.ok(payUrl);
    }

    /**
     * 查询订单状态
     * @param id
     * @return
     */
    @GetMapping("/state/{id}")
    public ResponseEntity<Integer> queryOrderState(@PathVariable("id") Long id){
        Integer state = orderService.queryOrderState(id);
        return ResponseEntity.ok(state);
    }
}
